package com.taoyibao.hongcanting.ui.admin.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.event.EventCurrentPage;
import com.taoyibao.hongcanting.event.EventTabCount;
import com.taoyibao.hongcanting.event.EventUpdataTask;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.TaskModel;
import com.taoyibao.hongcanting.model.TaskPageModel;
import com.taoyibao.hongcanting.ui.adapter.TaskAdapter;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.widget.RefreshRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TangAnna
 * @description: 进行中的任务
 * @date :${DATA} 16:04
 */
public class ProcessingTaskFragment extends Fragment implements OnRefreshListener {

    private int mStatus;//任务状态
    private List<TaskModel> mData;
    private TaskAdapter mAdapter;
    private RefreshRecyclerView mRefreshRecyclerView;
    private int mCurrentPage = 1;
    private int mMaxPageSize = 20000;
    private MyRunnable mRunnable;
    private Thread mTimerThread;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //优化刷新adapter的方法 只刷新计时器模块
                    mAdapter.notifyTime();
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.base_list_delegate, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        mStatus = getArguments().getInt(CodeConstant.STATUS);
        mRefreshRecyclerView = view.findViewById(R.id.refreshRecyclerView);

        mRefreshRecyclerView.getSmartRefreshLayout().setEnableLoadMore(false);
        mRefreshRecyclerView.getSmartRefreshLayout().setOnRefreshListener(this);

        mData = new ArrayList<>();
        mAdapter = new TaskAdapter(mData, getContext());
        mRefreshRecyclerView.getRecyclerView().setAdapter(mAdapter);
        getGiftOrderList();
    }

    /**
     * @param status 当前任务状态
     * @return
     */
    public static ProcessingTaskFragment getInstance(int status) {
        Bundle bundle = new Bundle();
        bundle.putInt(CodeConstant.STATUS, status);
        ProcessingTaskFragment fragment = new ProcessingTaskFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void getGiftOrderList() {
        JsonApiWrapper.getApiService().getGiftOrderList(SpUtils.getToken(), mStatus, mCurrentPage, mMaxPageSize)
                .compose(new DefaultTransformer<CompanyBaseModel<TaskPageModel>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<TaskPageModel>>(getContext(), true) {
                    @Override
                    public void onNext(CompanyBaseModel<TaskPageModel> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null ) {
                            List<TaskModel> orders_info = result.data.orders_info;
                            mData.clear();
                            mData.addAll(orders_info);
                            if (mData != null && mData.size() > 0) {//有数据
                                initTimeData();
                                mRefreshRecyclerView.setDataView();
                            } else {//没有数据
                                mRefreshRecyclerView.setEmptyView();
                            }
                        } else {
                            super.onNext(result);
                        }
                        mRefreshRecyclerView.setRefreshFinish();
                        sendCountEvent(mData.size());
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mRefreshRecyclerView.setEmptyView();
                        mRefreshRecyclerView.setRefreshFinish();
                        sendCountEvent(0);
                    }
                });
    }

    /**
     * 初始化计时器模块的数据
     */
    private void initTimeData() {
        //根据任务状态启动计时器
        if (mStatus == CodeConstant.TASK_STATUS_NEW || mStatus == CodeConstant.TASK_STATUS_ING) {
            if (mRunnable == null) {
                mRunnable = new MyRunnable(mData);
                mTimerThread = new Thread(mRunnable);
                mTimerThread.start();
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 更新计时器时间的线程
     */
    class MyRunnable implements Runnable {
        private List<TaskModel> mModelList;
        public boolean endThread;

        public MyRunnable(List<TaskModel> modelList) {
            mModelList = modelList;
        }

        @Override
        public void run() {
            try {
                while (!endThread) {
                    Thread.sleep(1000);
                    if (mModelList != null && mModelList.size() > 0) {
                        for (int i = 0; i < mModelList.size(); i++) {
                            //当前时间 单位秒
                            long currentTime = System.currentTimeMillis();
                            //计算出每个任务的发送时间与当前时间的时间差值
                            //时间转换
                            long counttime = currentTime - mModelList.get(i).update_at * 1000;
                            long hours = (counttime) / (1000 * 60 * 60);
                            long minutes = (counttime - hours * (1000 * 60 * 60)) / (1000 * 60);
                            long second = (counttime / 1000 - hours * 60 * 60 - minutes * 60);
                            //并保存在商品time这个属性内
                            String hoursStr = hours + "";
                            String minutesStr = minutes + "";
                            String secondStr = second + "";
                            if (hours < 10) {
                                hoursStr = "0" + hoursStr;
                            }
                            if (minutes < 10) {
                                minutesStr = "0" + minutesStr;
                            }
                            if (second < 10) {
                                secondStr = "0" + secondStr;
                            }
                            String finaltime = hoursStr + ":" + minutesStr + ":" + secondStr;
                            mModelList.get(i).timer = finaltime;
                            Message message = new Message();
                            message.what = 1;
                            //发送信息给handler
                            mHandler.sendMessage(message);
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        //停止线程
        if (mRunnable != null) {
            mRunnable.endThread = true;
            mTimerThread = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //重现创建线程
        if (mTimerThread == null && mRunnable != null && mData != null && mData.size() > 0) {
            mRunnable.endThread = false;
            mTimerThread = new Thread(mRunnable);
            mTimerThread.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mRunnable != null) {
            mRunnable.endThread = true;
            mTimerThread = null;
            mRunnable = null;
        }
    }


    /**
     * 更新任务状态收到消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdataTask(EventUpdataTask event) {
        if (getUserVisibleHint() && event != null && event.mTaskModel != null) {
            updataTask(event);
        } else {
            getGiftOrderList();
        }

    }

    /**
     * 更新任务状态
     */
    public void updataTask(EventUpdataTask data) {
        JsonApiWrapper.getApiService().updataTask(SpUtils.getToken(), data.mTaskModel.gift_order_id, data.status)
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(getContext(), true) {
                    @Override
                    public void onNext(CompanyBaseModel result) {
                        if (result.code == NetCode.HTTP_200) {
                            ToastUtils.showToast(CodeUtils.getIdString(R.string.admin_operatingSuccess));
                            sendEventChangePager();
                            getGiftOrderList();
                        } else {
                            super.onNext(result);
                        }
                    }
                });
    }

    /**
     * 发送消息切换页面
     */
    public void sendEventChangePager() {
        EventCurrentPage eventCurrentPage = new EventCurrentPage();
        eventCurrentPage.target = "AdminActivity";
        eventCurrentPage.mCurrentPage = 2;
        EventBus.getDefault().post(eventCurrentPage);
    }

    /**
     * 刷新操作
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getGiftOrderList();
    }

    /**
     * 收到切换页面的消息 刷新页面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPager(EventCurrentPage eventCurrentPage) {
        if (TextUtils.equals("AdminActivity", eventCurrentPage.target)) {
            getGiftOrderList();
        }
    }

    /**
     * 数量变化发送消息 每次请求接口时使用
     *
     * @param count
     */
    private void sendCountEvent(int count) {
        EventTabCount eventTabCount = new EventTabCount();
        eventTabCount.currentPager = 1;
        eventTabCount.count = count;
        EventBus.getDefault().post(eventTabCount);
    }
}
